<template>
  <div>
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <template v-if="isCertShow">
        <a-form-model-item required prop="certificateUser" class="beforeRequiredSign">
          <a-select v-model="model.certificateUser" placeholder="请选择证书" class="certBox" style="width: 100%" allowClear>
            <a-select-option v-for="(item, key) in cerListArr" :key="key" :value="item.value">{{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item required prop="certificatePwd" class="beforeRequiredSign">
          <a-input v-model="model.certificatePwd" type="password" class="certPws" id="user_pin" name="user_pin"
            size="large" placeholder="请输入证书密码" allowClear>
            <!-- <a-icon slot="prefix" type="lock" :style="{ fontSize: '18px', color: 'rgba(0,0,0,.55)' }" /> -->
          </a-input>
        </a-form-model-item>
      </template>
      <a-form-model-item required prop="username" class="beforeRequiredSign">
        <a-input v-model="model.username" size="large" placeholder="请输入用户名" allowClear>
          <a-icon slot="prefix" type="user" :style="{ fontSize: '18px', color: 'rgba(0,0,0,.55)' }" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item required prop="password" class="beforeRequiredSign">
        <a-input v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码"
          allowClear>
          <a-icon slot="prefix" type="lock" :style="{ fontSize: '18px', color: 'rgba(0,0,0,.55)' }" />
        </a-input>
        <div style="color: red;font-size: 15px;position:relative;padding: 0 10px">
          <span v-if="pass">{{ text }}</span>
        </div>
      </a-form-model-item>

      <a-row :gutter="0">
        <a-col :span="16">
          <a-form-model-item required prop="inputCode" class="beforeRequiredSign">
            <a-input v-model="model.inputCode" size="large" type="text" placeholder="请输入验证码">
              <a-icon slot="prefix" type="safety-certificate" :style="{ fontSize: '18px', color: 'rgba(0,0,0,.55)' }" />
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode" />
          <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode" />
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { emit } from 'process'
import Vue from 'vue'
import { mapActions } from 'vuex'

export default {
  name: 'LoginAccount',
  data() {
    return {
      pass: false,
      text: undefined,
      requestCodeSuccess: false,
      randCodeImage: '',
      currdatetime: '',
      loginType: 0,
      model: {
        certificateUser: [],
        certificatePwd: '',
        username: '',
        password: '',
        inputCode: ''
      },
      validatorRules: {
        certificateUser: [{
          required: true, message: '请选择证书!', validator: 'click'
        }],
        certificatePwd: [{
          required: true, message: '请输入证书密码!', validator: 'click'
        }],
        username: [
          { required: true, message: '请输入用户名!' },
          { validator: this.handleUsernameOrEmail }
        ],
        password: [{
          required: true, message: '请输入密码!', validator: 'click'
        }],
        inputCode: [{
          required: true, message: '请输入验证码!'
        }]
      },
      rememberMe: "",
      cerListArr: [],
      isCertShow: false,
      userSignCertB64: "",
      loginTag: 1 //默认0是签名登录，1是普通登录
    }
  },
  created() {
    // 默认情况有证书登录，参数type为1则没有证书登录
    // let type = this.getQueryString('type')
    // console.log("type：" + type)
    // if (type == '1') {
    //   this.isCertShow = false
    //   this.loginTag = 1
    // } else {
    //   this.isCertShow = true
    //   this.loginTag = 0
    // }
    // this.$emit("setCertShow", this.isCertShow)
    this.handleChangeCheckCode();
  },
  mounted() {
    //识别并获取证书列表数据
    // if (this.isCertShow) {
    //   enumDevice();
    //   let cerList = token.SOF_GetUserList();
    //   console.log("证书数量：" + cerList.length)
    //   if (cerList != null && cerList.length > 0) {
    //     for (var i = 0; i < cerList.length; i++) {
    //       this.cerListArr.push({ title: cerList[i][0], value: cerList[i][1] })
    //     }
    //   }
    // }
  },
  watch: {
    model: {
      deep: true,
      handler(a, b) {
        if (this.model.password === '') {
          this.pass = false
        }
      }
    }
  },
  methods: {
    ...mapActions(['Login']),
    /**刷新验证码*/
    handleChangeCheckCode() {
      this.currdatetime = new Date().getTime();
      this.model.inputCode = ''
      getAction(`/sys/randomImage/${this.currdatetime}`).then(res => {
        if (res.success) {
          this.randCodeImage = res.result
          this.requestCodeSuccess = true
        } else {
          this.$message.error(res.message)
          this.requestCodeSuccess = false
        }
      }).catch(() => {
        this.requestCodeSuccess = false
      })
    },
    handleUserPassword(val) {
      console.log(val)
      this.pass = true
      this.text = val
    },
    // 判断登录类型
    handleUsernameOrEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback) {
      let promiseArray = []
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs['form'].validateField(item, (err) => {
            if (!err) {
              resolve();
            } else {
              reject(err);
            }
          })
        });
        promiseArray.push(p)
      }
      Promise.all(promiseArray).then(() => {
        callback()
      }).catch(err => {
        callback(err)
      })
    },
    acceptUsername(username) {
      this.model['username'] = username
    },
    //账号密码登录
    handleLogin(rememberMe) {
      this.rememberMe = rememberMe
      let params = []
      if (this.isCertShow) {
        params = ['certificateUser', 'certificatePwd', 'username', 'password', 'inputCode']
      } else {
        params = ['username', 'password', 'inputCode']
      }
      this.validateFields(params, (err) => {
        if (!err) {
          if (this.isCertShow) {
            //验证pin口令，即证书密码
            var ret = verifyUserPin();  //证书密码输入框写上 id="user_pin" name="user_pin"
            // console.log("ret")
            // console.log(ret)
            if (ret != 0) {
              this.$emit('validateFail')
              return;
            }
            //导出证书
            // console.log(this.model.certificateUser)
            // exportUserCert(this.model.certificateUser, "1");
            this.userSignCertB64 = token.SOF_ExportUserCert(this.model.certificateUser, "1");
            // console.log("userSignCertB64")
            // console.log(this.userSignCertB64)
            this.validateCertGenRandom() //根据证书获取随机数
          } else {
            this.login() //普通登录
          }
        } else {
          this.$emit('validateFail')
        }
      })
    },
    login(params) {
      let loginParams = {
        username: this.model.username,
        password: this.model.password,
        captcha: this.model.inputCode,
        checkKey: this.currdatetime,
        remember_me: this.rememberMe,
        loginTag: this.loginTag
      }
      //加上证书验证参数
      if (params) {
        loginParams = Object.assign(loginParams, params)
      }
      console.log("登录参数", loginParams)
      this.Login(loginParams).then((res) => {
        this.$emit('success', res.result)
      }).catch((err) => {
        this.$emit('fail', err)
      });
    },
    //证书验证，获取随机数
    validateCertGenRandom() {
      let that = this
      postAction(`/sys/agw/validateCertGenRandom`, { userSignCertB64: this.userSignCertB64 }).then(res => {
        if (res.success) {
          let sRandomDataB64 = res.result //获取随机数
          // console.log("随机数：")
          // console.log(sRandomDataB64)
          let signed = signData(this.model.certificateUser, sRandomDataB64); //对随机数进行签名,加密
          // console.log("随机数加密：")
          // console.log(signed)
          if (signed != null && signed != "") {
            let params = {
              userSignCert: that.userSignCertB64,
              randomData: sRandomDataB64,
              signedDataB64: signed,
            }
            that.login(params) //证书登录
          }
        } else {
          this.$emit('validateFail')
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.$emit('validateFail')
        this.$message.error(res.message)
      })
    },
    getQueryString(name) {
      let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      let r = window.location.search.substr(1).match(reg)
      if (r != null) {
        return encodeURIComponent(r[2])
      }
      return null
    }
  }

}
</script>

<style scoped>
.beforeRequiredSign::before {
  position: absolute;
  left: -15px;
  top: 14px;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
</style>